#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API可用性诊断脚本
测试各个数据源的连通性
"""

import requests
import time

def test_eastmoney_api():
    """测试东方财富API"""
    print("=" * 60)
    print("【测试1】东方财富API - 股票列表")
    print("=" * 60)
    
    urls_to_test = [
        {
            'name': '方案A: push2.eastmoney.com',
            'url': 'http://push2.eastmoney.com/api/qt/clist/get',
            'params': {
                'pn': '1', 'pz': '20', 'po': '1', 'np': '1',
                'ut': 'bd1d9ddb04089700cf9c27f6f7426281',
                'fltt': '2', 'invt': '2', 'fid': 'f3',
                'fs': 'm:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23',
                'fields': 'f12,f14'
            }
        },
        {
            'name': '方案B: 82.push2.eastmoney.com',
            'url': 'http://82.push2.eastmoney.com/api/qt/clist/get',
            'params': {
                'pn': '1', 'pz': '20', 'po': '1', 'np': '1',
                'fltt': '2', 'invt': '2', 'fid': 'f3',
                'fs': 'm:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23',
                'fields': 'f12,f14'
            }
        },
        {
            'name': '方案C: quote.eastmoney.com',
            'url': 'http://quote.eastmoney.com/center/gridlist.html',
            'params': None
        }
    ]
    
    for test in urls_to_test:
        print(f"\n→ {test['name']}")
        print(f"  URL: {test['url']}")
        try:
            response = requests.get(
                test['url'], 
                params=test['params'],
                timeout=10,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                }
            )
            print(f"  状态码: {response.status_code}")
            if response.status_code == 200:
                content = response.text[:200] if response.text else "无内容"
                print(f"  响应: {content}...")
                if test['params'] and 'data' in response.text:
                    print("  ✓ API可用")
                elif not test['params']:
                    print("  ✓ 页面可访问")
            else:
                print(f"  ✗ HTTP错误: {response.status_code}")
        except requests.exceptions.Timeout:
            print("  ✗ 请求超时（可能是网络问题或API限流）")
        except requests.exceptions.ConnectionError as e:
            print(f"  ✗ 连接错误: {e}")
        except Exception as e:
            print(f"  ✗ 错误: {type(e).__name__} - {e}")
        time.sleep(1)


def test_akshare():
    """测试AkShare"""
    print("\n" + "=" * 60)
    print("【测试2】AkShare库")
    print("=" * 60)
    
    try:
        import akshare as ak
        print("✓ AkShare库已安装")
        
        print("\n→ 测试获取股票列表...")
        df = ak.stock_zh_a_spot_em()
        if not df.empty:
            print(f"  ✓ 成功获取 {len(df)} 支股票")
            print(f"  示例数据:\n{df.head(3)[['代码', '名称', '最新价']].to_string(index=False)}")
        else:
            print("  ✗ 获取数据为空")
            
    except ImportError:
        print("✗ AkShare未安装，请运行: pip install akshare")
    except Exception as e:
        print(f"✗ AkShare错误: {type(e).__name__} - {e}")


def test_tushare():
    """测试Tushare"""
    print("\n" + "=" * 60)
    print("【测试3】Tushare库（需要token）")
    print("=" * 60)
    
    try:
        import tushare as ts
        print("✓ Tushare库已安装")
        print("⚠️  注意: Tushare需要注册获取token")
        print("   注册地址: https://tushare.pro/register")
    except ImportError:
        print("✗ Tushare未安装，可选安装: pip install tushare")


def test_baostock():
    """测试Baostock"""
    print("\n" + "=" * 60)
    print("【测试4】Baostock库（免费无需token）")
    print("=" * 60)
    
    try:
        import baostock as bs
        print("✓ Baostock库已安装")
        
        print("\n→ 测试连接...")
        lg = bs.login()
        if lg.error_code == '0':
            print("  ✓ 登录成功")
            
            # 测试获取股票数据
            rs = bs.query_stock_basic()
            data = []
            while (rs.error_code == '0') & rs.next():
                data.append(rs.get_row_data())
            
            if data:
                print(f"  ✓ 成功获取 {len(data)} 支股票")
                print(f"  示例: {data[0][:3]}")
            
            bs.logout()
        else:
            print(f"  ✗ 登录失败: {lg.error_msg}")
            
    except ImportError:
        print("✗ Baostock未安装，可选安装: pip install baostock")
    except Exception as e:
        print(f"✗ Baostock错误: {type(e).__name__} - {e}")


def main():
    print("\n" + "=" * 60)
    print("A股数据API诊断工具")
    print("=" * 60)
    print("说明: 测试各个数据源的可用性\n")
    
    # 测试东方财富
    test_eastmoney_api()
    
    # 测试AkShare
    test_akshare()
    
    # 测试Tushare
    test_tushare()
    
    # 测试Baostock
    test_baostock()
    
    print("\n" + "=" * 60)
    print("【诊断建议】")
    print("=" * 60)
    print("1. 如果东方财富API可用 → 使用 stock_screener_eastmoney.py")
    print("2. 如果AkShare可用 → 使用 stock_screener.py")
    print("3. 如果都不可用:")
    print("   - 检查网络连接和防火墙")
    print("   - 尝试使用VPN或代理")
    print("   - 考虑使用Tushare（需注册）或Baostock")
    print("=" * 60 + "\n")


if __name__ == "__main__":
    main()
